//
//  AppDelegate.m
//  iRSSNews
//
//  Created by bk_sport on 12/28/12.
//  Copyright (c) 2012 bk_sport. All rights reserved.
//

#import "AppDelegate.h"
#import "FavoritesViewController.h"
#import "SettingsViewController.h"
#import "Category.h"
#import "Feed.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    // create a standardUserDefaults variable
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    // getting an NSString object
    NSString *preString = [standardUserDefaults stringForKey:@"timeToClear"];
    
    if ([preString length] == 0) {
        [standardUserDefaults setObject:NSLocalizedString(@"NoneKey", @"") forKey:@"timeToClear"];
        [standardUserDefaults synchronize];
    }
        
    if (self.fetchedCategories.fetchedObjects.count == 0) {
        [self initValuesCategories];
    }
    if (self.fetchedFeeds.fetchedObjects.count == 0) {
        [self initValuesFeeds];
    }
    
    NSError *error;
	if (![[self fetchedCategories] performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);
	}
    
    if (![[self fetchedFeeds] performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);
	}
    
    // getting a numberOfCategories object
    NSInteger numberOfCategories = [standardUserDefaults integerForKey:@"numberOfCategories"];
    if (numberOfCategories == 0) {
        [standardUserDefaults setInteger:self.fetchedCategories.fetchedObjects.count forKey:@"numberOfCategories"];
        [standardUserDefaults synchronize];
    }
    
    NSInteger numberOfFeeds = [standardUserDefaults integerForKey:@"numberOfFeeds"];
    if (numberOfFeeds == 0) {
        [standardUserDefaults setInteger:self.fetchedFeeds.fetchedObjects.count forKey:@"numberOfFeeds"];
        [standardUserDefaults synchronize];
    }

    _categories = [[CategoriesViewController alloc] init];
    _feeds = [[FeedsViewController alloc] init];
    _settings = [[SettingsViewController alloc] init];
    
    UINavigationController *navi_categories = [[UINavigationController alloc] initWithRootViewController:_categories];
    navi_categories.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TitleNewsKey", @"") image:[UIImage imageNamed:@"ic_tabbar_news"] tag:0];
    navi_categories.navigationBar.barStyle = UIBarStyleBlack;
    
    FavoritesViewController *favorites = [[FavoritesViewController alloc] init];
    UINavigationController *navi_favorites = [[UINavigationController alloc] initWithRootViewController:favorites];
    navi_favorites.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TitleFavoritesKey", @"") image:[UIImage imageNamed:@"ic_tabbar_favorites"] tag:1];
    navi_favorites.navigationBar.barStyle = UIBarStyleBlack;
    
    UINavigationController *navi_settings = [[UINavigationController alloc] initWithRootViewController:_settings];
    navi_settings.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TitleSettingsKey", @"") image:[UIImage imageNamed:@"ic_tabbar_settings"] tag:2];
    navi_settings.navigationBar.barStyle = UIBarStyleBlack;
    
    UITabBarController *tabBar = [[UITabBarController alloc] init];
    tabBar.viewControllers = @[navi_categories, navi_favorites, navi_settings];
    self.window.rootViewController = tabBar;
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"iRSSNews" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"iRSSNews.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


-(void)initValuesCategories{
    
    
    if (![[self fetchedCategories] performFetch:nil]) {
        NSLog(@"Loi fetched perform");
        return;
    }
    else{
        if (self.fetchedCategories.fetchedObjects.count > 0) {
            return;
        }
    }
    NSManagedObjectContext *context = [self managedObjectContext];
    
    
    Category *item = [NSEntityDescription
                            insertNewObjectForEntityForName:@"Category"
                            inManagedObjectContext:context];
    item.id = [NSNumber numberWithInt:0];
    item.name = @"Xa Hoi";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
    item.id = [NSNumber numberWithInt:1];
    item.name = @"Bong Da";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:2];
    item.name = @"Kinh Te";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:3];
    item.name = @"Giao Duc";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:4];
    item.name = @"Thoi Trang";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
    item.id = [NSNumber numberWithInt:5];
    item.name = @"An Ninh";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:6];
    item.name = @"Quoc Te";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:7];
    item.name = @"Ngoai Giao";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:8];
    item.name = @"Chinh Tri";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Category"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:9];
    item.name = @"Noi Tro";
    item.numberOfNewNews=[NSNumber numberWithInt:30];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
}


-(void) initValuesFeeds
{
    if (![[self fetchedFeeds] performFetch:nil]) {
        NSLog(@"Loi fetched perform");
        return;
    }
    else{
        if (self.fetchedFeeds.fetchedObjects.count > 0) {
            return;
        }
    }
    NSManagedObjectContext *context = [self managedObjectContext];
    
    
    Feed *item = [NSEntityDescription
                       insertNewObjectForEntityForName:@"Feed"
                       inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:0];
    item.name = @"Dan tri";
    item.numberOfNewNews=[NSNumber numberWithInt:10];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Feed"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:1];
    item.name = @"VnExpress";
    item.numberOfNewNews=[NSNumber numberWithInt:10];
    
    item = [NSEntityDescription
            insertNewObjectForEntityForName:@"Feed"
            inManagedObjectContext:context];
        item.id = [NSNumber numberWithInt:2];
    item.name = @"24h";
    item.numberOfNewNews=[NSNumber numberWithInt:10];
    
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
}


#pragma mark - fetchCategories

- (NSFetchedResultsController *)fetchedCategories
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    if (_fetchedCategories != nil) {
        return _fetchedCategories;
    }
    static NSString *EntityName = @"Category";
    static NSString *CacheName = @"Category";
    [NSFetchedResultsController deleteCacheWithName:@"Category"];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:EntityName inManagedObjectContext:appDelegate.managedObjectContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
    fetchRequest.entity = entity;
    fetchRequest.sortDescriptors = @[sort];
    fetchRequest.fetchBatchSize = 20;
    
    
    _fetchedCategories = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:CacheName];
    
    return _fetchedCategories;
}

#pragma mark - fetchedFeed

- (NSFetchedResultsController *)fetchedFeeds
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    if (_fetchedFeeds != nil) {
        return _fetchedFeeds;
    }
    static NSString *EntityName = @"Feed";
    static NSString *CacheName = @"Feed";
    [NSFetchedResultsController deleteCacheWithName:@"Feed"];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:EntityName inManagedObjectContext:appDelegate.managedObjectContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
    fetchRequest.entity = entity;
    fetchRequest.sortDescriptors = @[sort];
    fetchRequest.fetchBatchSize = 20;
    
    
    _fetchedFeeds = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:CacheName];
    
    return _fetchedFeeds;
}

@end
